package com.itdr.protal.service.impl;

import cn.hutool.cache.Cache;
import cn.hutool.cache.CacheUtil;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itdr.common.Const;
import com.itdr.common.ServerResponse;
import com.itdr.pojo.User;
import com.itdr.pojo.vo.UserVO;
import com.itdr.protal.mapper.UserMapper;
import com.itdr.protal.service.IUserService;
import com.itdr.utils.TokenUtil;
import com.itdr.utils.VOUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author AirZhang
 * @since 2020-10-20
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Resource
    UserMapper userMapper;

    @Override
    public ServerResponse register(User u) {
        // 1.查询要注册的用户是否已存在
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("username", u.getUsername()));
        if (user != null) {
            return ServerResponse.toFail(Const.UserEnum.REPEAT_USERNAME.getCode(), Const.UserEnum.REPEAT_USERNAME.getDesc());
        }

        // 2.在不存在的情况下，注册新用户
        u.setCreateTime(DateUtil.date());
        u.setUpdateTime(DateUtil.date());
        // 这里进行了MD5加密
        u.setPassword(DigestUtil.md5Hex(u.getPassword()));

        int insert = userMapper.insert(u);
        if (insert <= 0) {
            return ServerResponse.toFail(Const.UserEnum.FAIL_INSERT_USERNAME.getCode(), Const.UserEnum.FAIL_INSERT_USERNAME.getDesc());
        }

        // 返回成功数据
        return ServerResponse.toSuccess(u.getUsername());
    }

    @Override
    public ServerResponse login(User u) {
        // 1.查询登录用户是否存在
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("username", u.getUsername()));
        if (user == null) {
            return ServerResponse.toFail(Const.UserEnum.EMPTY_USERNAME.getCode(), Const.UserEnum.EMPTY_USERNAME.getDesc());
        }
        // 2.存在的情况下，密码是否相同
        if (!user.getPassword().equals(DigestUtil.md5Hex(u.getPassword()))) {
            return ServerResponse.toFail(
                    Const.UserEnum.ERROR_USERNAMEORPASSWORD.getCode(),
                    Const.UserEnum.ERROR_USERNAMEORPASSWORD.getDesc());
        }
        // 3.把密码置空
        UserVO userVO = VOUtil.getUserVO(user);
        return ServerResponse.toSuccess(userVO);
    }

    @Override
    public ServerResponse gmsg(UserVO uvo, User u) {
        // 1.判断要修改的数据是否已被使用
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("email", u.getEmail()));
        User user2 = userMapper.selectOne(new QueryWrapper<User>().eq("phone", u.getPhone()));
        if (user != null || user2 != null) {
            return ServerResponse.toFail(
                    Const.UserEnum.USED_EMAILORPHONE.getCode(),
                    Const.UserEnum.USED_EMAILORPHONE.getDesc());
        }

        // 2.在未被使用的情况下，修改数据
        u.setId(uvo.getId());
        int i = userMapper.updateById(u);
        if (i <= 0) {
            return ServerResponse.toFail(
                    Const.UserEnum.FAIL_MSG.getCode(),
                    Const.UserEnum.FAIL_MSG.getDesc());
        }

        // 成功返回修改后的信息
        User user3 = userMapper.selectById(uvo.getId());
        UserVO userVO = VOUtil.getUserVO(user3);
        return ServerResponse.toSuccess(userVO);
    }

    @Override
    public ServerResponse yzUser(UserVO uvo, User u) {
        // 1.查找当前登录用户信息的密码
        User user = userMapper.selectById(uvo.getId());
        // 2.比对传参的密码是否匹配
        String password = u.getPassword();
        String s = DigestUtil.md5Hex(password);
        if (!user.getPassword().equals(s)) {
            return ServerResponse.toFail(
                    Const.UserEnum.DIFFERENT_USER.getCode(),
                    Const.UserEnum.DIFFERENT_USER.getDesc());
        }

        // 3.创建令牌并放入缓存
        String token = TokenUtil.putInCache(10, Const.TMBNAME);
        return ServerResponse.toSuccess(token);
    }

    @Override
    public ServerResponse gmb(UserVO uvo, User u, String tk) {
        // 1.判断令牌是否存在
        // 2.判断令牌是否匹配
        Map<Boolean, String> booleanStringMap = TokenUtil.yzToken(tk, Const.TMBNAME);
        for (Boolean aBoolean : booleanStringMap.keySet()) {
            if (!aBoolean) {
                return ServerResponse.toFail(Const.FAIL, booleanStringMap.get(aBoolean));
            }
        }

        // 3.修改密保信息
        u.setId(uvo.getId());
        int i = userMapper.updateById(u);
        if (i <= 0) {
            return ServerResponse.toFail(
                    Const.UserEnum.FAIL_MSG.getCode(),
                    Const.UserEnum.FAIL_MSG.getDesc());
        }
        return ServerResponse.toSuccess(u.getQuestion());
    }

    @Override
    public ServerResponse ugmm(UserVO uvo, String oldPassWord, String newPassWord) {
        // 1.查找当前登录用户信息的密码
        User user = userMapper.selectById(uvo.getId());
        // 2.比对传参的密码是否匹配
        String s = DigestUtil.md5Hex(oldPassWord);
        if (!user.getPassword().equals(s)) {
            return ServerResponse.toFail(
                    Const.UserEnum.DIFFERENT_USER.getCode(),
                    Const.UserEnum.DIFFERENT_USER.getDesc());
        }
        // 3.身份验证通过，修改原始密码

        int i = userMapper.update(null,
                new UpdateWrapper<User>().set("password", DigestUtil.md5Hex(newPassWord)).eq("id", uvo.getId()));
        if (i <= 0) {
            return ServerResponse.toFail(
                    Const.UserEnum.FAIL_UPDATE_PASSWORD.getCode(),
                    Const.UserEnum.FAIL_UPDATE_PASSWORD.getDesc());
        }

        return ServerResponse.toSuccess(Const.SUCCESS_MSG);
    }

    @Override
    public ServerResponse wpas(String userName) {
        // 1.当前账户是否存在
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("username", userName));
        if (user == null) {
            return ServerResponse.toFail(
                    Const.UserEnum.EMPTY_USERNAME.getCode(),
                    Const.UserEnum.EMPTY_USERNAME.getDesc());
        }
        // 2.判断用户是否设置过密保
        if (!(user.getQuestion() != null && !(user.getQuestion().equals("")))) {
            return ServerResponse.toFail(
                    Const.UserEnum.NO_MB.getCode(),
                    Const.UserEnum.NO_MB.getDesc());
        }
        // 3.返回密保问题
        return ServerResponse.toSuccess(user.getQuestion());
    }

    @Override
    public ServerResponse mbAnswer(String userName,String answer) {
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("username", userName));
        if(!user.getAnswer().equals(answer)){
            return ServerResponse.toFail(Const.UserEnum.FAIL_VERIFY_MB.getCode(),Const.UserEnum.FAIL_VERIFY_MB.getDesc());
        }
        String s = TokenUtil.putInCache(10, Const.GMMNAME);
        return ServerResponse.toSuccess(s);
    }

    @Override
    public ServerResponse gmm(String userName, String newPassWord, String tk) {
        // 1.判断令牌是否存在
        // 2.判断令牌是否匹配
        Map<Boolean, String> booleanStringMap = TokenUtil.yzToken(tk, Const.GMMNAME);
        for (Boolean aBoolean : booleanStringMap.keySet()) {
            if (!aBoolean) {
                return ServerResponse.toFail(Const.FAIL, booleanStringMap.get(aBoolean));
            }
        }
        // 2.修改用户密码
        int update = userMapper.update(null,
                new UpdateWrapper<User>().set("password", DigestUtil.md5Hex(newPassWord)).eq("username", userName));
        if (update <= 0) {
            return ServerResponse.toFail(Const.UserEnum.FAIL_UPDATE_PASSWORD.getCode(), Const.UserEnum.FAIL_UPDATE_PASSWORD.getDesc());
        }

        // 成功返回
        return ServerResponse.toSuccess(Const.SUCCESS_MSG);
    }
}
